package com.mediocre.service.impl;

import com.mediocre.service.ICommonService;
import com.mediocre.util.BizUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class CommonService implements ICommonService {

    @Value("${cnblogs.host}")
    private String host;
    @Value("${cnblogs.msg.uri}")
    private String uri;

    @Override
    public String msg() {
        /*System.out.println("host === " + host);
        System.out.println("uri === " + uri);
        */
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
            httpClient = HttpClientBuilder.create().build();
            // assemble url
            // eg. https://i.cnblogs.com/api/msg
            StringBuilder msgUrl = new StringBuilder(host).append(uri);
            log.info("msgUrl === {}", msgUrl);
            // create request
            HttpGet httpGet = new HttpGet(msgUrl.toString());
            // 配置信息
            BizUtils.configRequest(httpGet);
            // 由客户端执行(发送)请求
            httpResponse = httpClient.execute(httpGet);
            // 获取并返回响应内容
            return BizUtils.getResponseStr(httpResponse);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close resources
            BizUtils.closeResources(httpResponse, httpClient);
        }
        return null;
    }
}
